import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

export const useStandaloneTaskStore = defineStore('standaloneTask', () => {
  // 状态
  const taskList = ref([])
  const selectedTaskId = ref('')
  const taskConfig = ref('')
  const taskResult = ref('')
  const isRunning = ref(false)
  const isAppIdle = ref(true)

  // 计算属性
  const hasTasks = computed(() => taskList.value.length > 0)
  const selectedTask = computed(() => 
    taskList.value.find(task => task.id === selectedTaskId.value)
  )
  const canRunTask = computed(() => hasTasks.value && !isRunning.value && isAppIdle.value)

  // 动作
  async function initializeTaskPanel() {
    await updateTaskList()
  }

  async function updateTaskList() {
    try {
      const taskClassTable = await agencyAsync.getTaskClassTable()
      
      if (!taskClassTable) {
        taskList.value = []
        selectedTaskId.value = ''
        taskConfig.value = ''
        return
      }
      
      taskList.value = Object.entries(taskClassTable).map(([id, info]) => ({
        id,
        title: info.title,
        defaultConfig: info.defaultConfig
      }))

      if (taskList.value.length > 0) {
        selectedTaskId.value = taskList.value[0].id
        taskConfig.value = taskList.value[0].defaultConfig ? JSON.stringify(taskList.value[0].defaultConfig, null, 2) : ''
      } else {
        selectedTaskId.value = ''
        taskConfig.value = ''
      }
    } catch (error) {
      console.error('Failed to update task list:', error)
      taskList.value = []
      selectedTaskId.value = ''
      taskConfig.value = ''
    }
  }

  function selectTask(taskId) {
    selectedTaskId.value = taskId
    const task = taskList.value.find(t => t.id === taskId)
    if (task) {
      taskConfig.value = task.defaultConfig ? JSON.stringify(task.defaultConfig, null, 2) : ''
    }
  }

  async function runTask() {
    if (!selectedTaskId.value || isRunning.value) return

    try {
      isRunning.value = true
      taskResult.value = 'Running...'
      
      const result = await agencyAsync.runStandaloneTask(selectedTaskId.value, taskConfig.value)
      taskResult.value = `Result: ${result[0]}`
    } catch (error) {
      console.error('Failed to run task:', error)
      taskResult.value = 'Error: ' + error.message
    } finally {
      isRunning.value = false
    }
  }

  async function updateRunButton() {
    isAppIdle.value = await agencyAsync.getAppStatus() === appoxEnums.ApplicationStatus.Idle
  }

  return {
    // 状态
    taskList,
    selectedTaskId,
    taskConfig,
    taskResult,
    isRunning,
    isAppIdle,
    // 计算属性
    hasTasks,
    selectedTask,
    canRunTask,
    // 动作
    initializeTaskPanel,
    updateTaskList,
    selectTask,
    runTask,
    updateRunButton
  }
})